//
//  STSportingViewController.m
//  STBest
//
//  Created by apple on 2017/8/28.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "STSportingViewController.h"
#import "STSportingMapViewController.h"
#import "STSportingManager.h"
#import "STCycleAnimator.h"
#import "UIColor+Define.h"
#import "STCaptureImageViewController.h"

@interface STSportingViewController ()
@property (weak, nonatomic) IBOutlet UIButton *pauseButton;
@property (weak, nonatomic) IBOutlet UIButton *resumeButton;
@property (weak, nonatomic) IBOutlet UIButton *finishButton;
@property (weak, nonatomic) IBOutlet UIImageView *gpsStateImageView;
@property (weak, nonatomic) IBOutlet UILabel *distanceLabel;
@property (weak, nonatomic) IBOutlet UILabel *durationLabel;
@property (weak, nonatomic) IBOutlet UILabel *avgSpeedLabel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *ResumeTrailing;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *FinishLeading;

@end

@implementation STSportingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self refreshUIWithState:_SportingMgr.state];
    [self refreshUIWithGPSState:_SportingMgr.gpsState];
    [self setupBackground];
    [self setupNotifications];
}

#pragma mark - Action打开地图方法 -
- (IBAction)ActionOpenMap:(UIButton *)sender {
    UIStoryboard  *sb = [UIStoryboard storyboardWithName:@"Sporting" bundle:nil];
    
    STSportingMapViewController  *vc = [sb instantiateViewControllerWithIdentifier:@"STSportingMapViewController"];
     STCycleAnimator *anim = [STCycleAnimator new];
    anim.centerPoint = sender.center;
    vc.animator = anim;
    
    [self presentViewController:vc animated:YES completion:nil];
    
}

- (void)setupNotifications{
    // 监视线段被添加后回调
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sporingTrackingLineDidBeGeneratedNotification:) name:STSporingTrackingLineDidBeGeneratedNotification object:_SportingMgr];
    
    // 监听运动状态发生变化
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sportingStateDidChangedNotification:) name:STSportingStateDidChangedNotification object:_SportingMgr];
    
    // 监听GPS状态变化
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sportingGPSStateDidChangedNotification:) name:STSportingGPSStateDidChangedNotification object:_SportingMgr];
}


- (void)teardownNotifications {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


// 运动状态发生变化时回调
- (void)sportingStateDidChangedNotification:(NSNotification *)notification {
    STSportingState state = [notification.userInfo[kState] integerValue];
    [self refreshUIWithState:state];
}

#pragma mark - 构建界面 -
- (void)setupBackground {
    // 1. 让UI提供背景图
    
    // 2. 使用代码方式构建背景
    // 创建渐变层
    CAGradientLayer *backgroundLayer = [CAGradientLayer new];
    // 设置大小
    backgroundLayer.frame = self.view.bounds;
    
    // 设置渐变属性
    // 渐变颜色区别,注意：内部数组不能用 UIColor，只能用  CGColorRef
    /*
     CGColorRef color1 = [UIColor redColor].CGColor;
     CGColorRef color2 = [UIColor yellowColor].CGColor;
     CGColorRef color3 = [UIColor blueColor].CGColor;
     
     layer.colors = @[(__bridge id)color1,(__bridge id)color2,(__bridge id)color3];
     */
    
    backgroundLayer.colors = @[
                               (__bridge id)[UIColor colorWithHexString:@"0x0e1428"].CGColor,
                               (__bridge id)[UIColor colorWithHexString:@"0x406479"].CGColor,
                               (__bridge id)[UIColor colorWithHexString:@"0x406578"].CGColor
                               ];
    
    // 设置渐变百分比
    // 渐变轨迹(所占的具体颜色值位置)(0-1.0)
    // 渐变的最终颜色点的百分比位置
    backgroundLayer.locations = @[@(0.0),@(0.5),@(1.0)];
    
    // 设置渐变方向 layer坐标系 左下角(0,0)
    backgroundLayer.startPoint = CGPointMake(1, 0);
    backgroundLayer.endPoint =CGPointMake(1, 1);
    
    
    // 添加层
    [self.view.layer insertSublayer:backgroundLayer atIndex:0];
    
    
}

// 当线段被生成的时候引发通知
- (void)sporingTrackingLineDidBeGeneratedNotification:(NSNotification *)notification {
    // 设置运动距离
    self.distanceLabel.text = [NSString stringWithFormat:@"%.2f",_SportingMgr.sportingsportingTracking.distance];
    
    // 设置时长
    self.durationLabel.text = _SportingMgr.sportingsportingTracking.durationString;
    
    // 平均速度
    self.avgSpeedLabel.text = [NSString stringWithFormat:@"%.2f",_SportingMgr.sportingsportingTracking.avgSpeed];
    
}
#pragma mark - 刷新UI -
// 描述 state 和界面之间的关系
- (void)refreshUIWithState:(STSportingState)state {
    
    
    if(state == STSportingStateSporting){
        //开始运动 -> 两个按钮合起来
        self.ResumeTrailing.constant = 0;
        self.FinishLeading.constant = 0;
        
        [self.view layoutIfNeeded];
        self.resumeButton.hidden = NO;
        self.finishButton.hidden = NO;
        self.pauseButton.hidden = YES;
        
        [UIView animateWithDuration:0.3 animations:^{
            self.ResumeTrailing.constant = -100;
            self.FinishLeading.constant = -100;
            [self.view layoutIfNeeded];
        } completion:^(BOOL finished) {
            self.pauseButton.hidden = NO;
            self.resumeButton.hidden = YES;
            self.finishButton.hidden = YES;
        }];
    }else if(state == STSportingStatePaused){
        
        self.ResumeTrailing.constant = -100;
        self.FinishLeading.constant = -100;
        [self.view layoutIfNeeded];
        
        self.resumeButton.hidden = NO;
        self.finishButton.hidden = NO;
        self.pauseButton.hidden = YES;
        
        [UIView animateWithDuration:0.3 animations:^{
            
            self.ResumeTrailing.constant = 0;
            self.FinishLeading.constant = 0;
            [self.view layoutIfNeeded];
        } completion:^(BOOL finished) {
           
            self.resumeButton.hidden = NO;
            self.finishButton.hidden = NO;
            self.pauseButton.hidden = YES;
        }];
        
    }
//    switch (state) {
//        case STSportingStateUnsport:
//            
//            self.pauseButton.hidden = YES;
//            self.resumeButton.hidden = YES;
//            self.finishButton.hidden = YES;
//            break;
//            
//        case STSportingStateSporting:
//            self.pauseButton.hidden = NO;
//            self.resumeButton.hidden = YES;
//            self.finishButton.hidden = NO;
//            break;
//            
//        case STSportingStatePaused:
//            self.pauseButton.hidden = YES;
//            self.resumeButton.hidden = NO;
//            self.finishButton.hidden = YES;
//            break;
//        default:
//            break;
//    }
}
- (void)sportingGPSStateDidChangedNotification:(NSNotification *)notification {
    STSportingGPSState state =[notification.userInfo[kGPSState] integerValue];
    [self refreshUIWithGPSState:state];
}

#pragma mark - 刷新UI -
// 描述 gps状态 和界面之间关系
- (void)refreshUIWithGPSState:(STSportingGPSState)gpsState {
    switch (gpsState) {
        case STSportingGPSStateDisconnect:
            self.gpsStateImageView.image = _I(@"ic_sport_gps_disconnect");
            break;
        case STSportingGPSStateGood:
            self.gpsStateImageView.image = _I(@"ic_sport_gps_connect_3");
            break;
        case STSportingGPSStateNormal:
            self.gpsStateImageView.image = _I(@"ic_sport_gps_connect_2");
            break;
            
        case STSportingGPSStateBad:
            self.gpsStateImageView.image = _I(@"ic_sport_gps_connect_1");
            break;
            
        default:
            break;
    }
}


- (void)dealloc{
    [self teardownNotifications];
}

- (IBAction)actionPause:(id)sender {
    [_SportingMgr pause];
}

- (IBAction)actionResume:(id)sender {
    [_SportingMgr resume];
}
- (IBAction)actionFinish:(id)sender {
    [_SportingMgr finish];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)actionTakeImage:(id)sender {
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Sporting" bundle:nil];
    STCaptureImageViewController *vc = [sb instantiateViewControllerWithIdentifier:@"STCaptureImageViewController"];
    
    [self presentViewController:vc animated:YES completion:nil];
}

@end
